package com.myself.community.event;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.myself.community.entity.DiscussPost;
import com.myself.community.entity.Event;
import com.myself.community.entity.Message;
import com.myself.community.service.DiscussPostService;
import com.myself.community.service.ElasticSearchService;
import com.myself.community.service.MessageService;
import com.myself.community.utils.Code;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 消费者：接收（消费）事件数据信息
 */
@Slf4j
@Component
public class EventConsumer{
    @Autowired
    private MessageService messageService;

    @Autowired
    private DiscussPostService discussPostService;

    @Autowired
    private ElasticSearchService elasticSearchService;

    /**
     * 消费评论、赞、关注事件，发送系统消息
     * @param record
     */
    @KafkaListener(topics = {Code.TOPIC_COMMENT, Code.TOPIC_LIKE, Code.TOPIC_FOLLOW})//评论、赞、关注
    public void handleCommentMessage(ConsumerRecord record) {
        if (record == null || record.value() == null) {
            log.error("消息的内容为空!");
            return;
        }
        //获取的消息转换成事件对象
        Event event = JSON.parseObject(record.value().toString(), Event.class);
        if (event == null) {
            log.error("消息格式错误!");
            return;
        }

        // 发送站内通知：系统通知用户
        Message message = new Message();
        message.setFromId(Code.SYSTEM_USER_ID);//系统为发送方：id=1
        message.setToId(event.getEntityUserId());//接收方用户id
        message.setConversationId(event.getTopic());//会话id指定成主题
        message.setCreateTime(new Date());
        //封装信息内容：content:其中包含事件触发者id、事件类型、事件对象id
        Map<String, Object> content = new HashMap<>();
        content.put("userId", event.getUserId());
        content.put("entityType", event.getEntityType());
        content.put("entityId", event.getEntityId());

        //查看事件中是否存在额外数据：data中有没有数据
        if (!event.getData().isEmpty()) {
            for (Map.Entry<String, Object> entry : event.getData().entrySet()) {
                content.put(entry.getKey(), entry.getValue());
            }
        }
        //存储信息内容
        message.setContent(JSON.toJSONString(content));
        messageService.addMessage(message);
    }

    // 消费发帖事件
    @KafkaListener(topics = {Code.TOPIC_PUBLISH})
    public void handlePublishMessage(ConsumerRecord record){
        if(record==null || record.value()==null){
            log.error("消息内容为空！");
            return;
        }
        Event event = JSONObject.parseObject(record.value().toString(),Event.class);
        if(event == null){
            log.error("消息格式错误！");
            return;
        }
        //从数据库中查询出发布的帖子
        DiscussPost post = discussPostService.findDiscussPostById(event.getEntityId());

        //将帖子存储到es服务器
        elasticSearchService.saveDiscussPost(post);
    }

    // 消费删除事件
    @KafkaListener(topics = {Code.TOPIC_PUBLISH})
    public void handleDeleteMessage(ConsumerRecord record){
        if(record==null || record.value()==null){
            log.error("消息内容为空！");
            return;
        }
        Event event = JSONObject.parseObject(record.value().toString(),Event.class);
        if(event == null){
            log.error("消息格式错误！");
            return;
        }
        elasticSearchService.deleteDiscussPost(event.getEntityId());
    }
}
